import React, { useEffect, useState } from 'react';
import { Form, Spin, Input, Popover, Icon } from 'antd';
import { useRequest } from '@/hooks';
import moment from 'moment';
import { size } from 'lodash';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { BaseInfo, WorkCountersign, AssetCountersign, OfficeDepotCountersign, FinanceCountersign } from './components';

import styles from './index.less';
import { queryTableInitData } from './service';
import { getEmployeeInfo } from '../TurnoverProcess/service';

// 离职交接
const Handover = ({ dataSource, form, wrapperLayout }) => {
    const { children: list = [], formValueMap } = dataSource;
    const [userInfo, setUserInfo] = useState({});
    const [tableSource, setTableSource] = useState(null);
    const [tableLoading, setTableLetloading] = useState(false);
    const { getFieldDecorator, setFieldsValue } = form;

    // 通过employeeCode拿取行政机构，主要用来兼容旧数据没有行政机构
    const { run: runUserInfo } = useRequest(params => getEmployeeInfo(params), {
        manual: true
    });

    useEffect(() => {
        const fetchTableData = async () => {
            setTableLetloading(true);
            const result = await queryTableInitData();
            if (result.code === 10000) {
                setTableSource(result.data);
            }
            setTableLetloading(false);
        };
        fetchTableData();
    }, []);

    useEffect(() => {
        if (size(formValueMap) > 0) {
            const {
                employeeCode,
                employeeName,
                organizationName,
                positionName,
                companyName,
                hopeResignationDate,
                turnoverLink,
                leaveProcessInstanceName,
                rankValue
            } = formValueMap || {};

            const fetchUserInfo = async () => {
                // 旧的流程没有行政机构，走接口去获取
                let fetchCompanyName;
                if (size(companyName) === 0) {
                    const result = await runUserInfo(employeeCode);
                    fetchCompanyName = result?.data[0]?.companyName;
                }
                setUserInfo({
                    employeeName,
                    organizationName,
                    positionName,
                    hopeResignationDate,
                    turnoverLink,
                    leaveProcessInstanceName,
                    rankValue,
                    companyName: companyName || fetchCompanyName
                });
            };
            fetchUserInfo();
        }
    }, [formValueMap, runUserInfo]);

    useEffect(() => {
        if (size(tableSource) > 0) {
            const { works, assets, offices, finance } = tableSource;
            const { workCountersign, assetCountersign, officeDepotCountersign, financeCountersign } =
                formValueMap || {};
            setFieldsValue({
                workCountersign: size(workCountersign) > 0 ? workCountersign : works,
                assetCountersign: size(assetCountersign) > 0 ? assetCountersign : assets,
                officeDepotCountersign: size(officeDepotCountersign) > 0 ? officeDepotCountersign : offices,
                financeCountersign: size(financeCountersign) > 0 ? financeCountersign : finance
            });
        }
    }, [tableSource, formValueMap, setFieldsValue]);

    useEffect(() => {
        const arr = form.getFieldValue('workCountersign');
        if (size(arr) > 0) {
            setTimeout(() => {
                const temp = arr.map(item => item?.successor?.key).join(',');
                form.setFieldsValue({ pendingApprovers: temp });
            }, 10);
        }
    }, [form.getFieldValue('workCountersign')]);

    const tableRules = [
        { required: true, message: ' ' },
        {
            validator(_, value, callback) {
                const arr = value.filter(subItem => subItem.isValidatorPass === false);
                if (!value || value?.length === 0) {
                    callback('必须选择处理情况');
                } else if (arr?.length > 0) {
                    callback('表格中有未处理的信息');
                } else {
                    callback();
                }
            }
        }
    ];

    return (
        <div className={styles.handoverWrapper}>
            <div style={{ fontSize: 16, fontWeight: 'bold' }}>基本信息</div>
            <BaseInfo user={userInfo} wrapperLayout={wrapperLayout} />

            <Spin spinning={tableLoading}>
                {tableSource &&
                    list.length > 0 &&
                    list.map(item => {
                        const { formId, label, extra, initialValue, rules } = item;
                        const { employeeCode, hopeResignationDate } = formValueMap || {};
                        const propsObj = { employeeCode };
                        if (item.tag === 'Table') {
                            switch (item.formId) {
                                case 'workCountersign':
                                    return (
                                        <Form.Item key={formId} label={label} {...wrapperLayout}>
                                            {getFieldDecorator(formId, {
                                                initialValue,
                                                rules: [
                                                    { required: true, message: ' ' },
                                                    {
                                                        validator(_, value, callback) {
                                                            const arr = value.filter(
                                                                subItem => subItem.isValidatorPass === false
                                                            );
                                                            if (!value || value?.length === 0) {
                                                                callback('请输入工作交接信息');
                                                            } else if (arr?.length > 0) {
                                                                callback('表格中有未填写完整的信息');
                                                            } else {
                                                                callback();
                                                            }
                                                        }
                                                    }
                                                ]
                                            })(<WorkCountersign config={item} />)}
                                        </Form.Item>
                                    );
                                case 'assetCountersign':
                                    return (
                                        <Form.Item key={formId} label={label} {...wrapperLayout}>
                                            {getFieldDecorator(formId, {
                                                initialValue,
                                                rules: tableRules
                                            })(<AssetCountersign config={item} />)}
                                        </Form.Item>
                                    );
                                case 'officeDepotCountersign':
                                    return (
                                        <Form.Item key={formId} label={label} {...wrapperLayout}>
                                            {getFieldDecorator(formId, {
                                                initialValue,
                                                rules: tableRules
                                            })(<OfficeDepotCountersign config={item} />)}
                                        </Form.Item>
                                    );
                                case 'financeCountersign':
                                    return (
                                        <Form.Item key={formId} label={label} {...wrapperLayout}>
                                            {getFieldDecorator(formId, {
                                                initialValue,
                                                rules: tableRules
                                            })(<FinanceCountersign config={item} />)}
                                        </Form.Item>
                                    );
                                default:
                                    return null;
                            }
                        }
                        // 作为表单里面的联系人，不显示，主要用来在流程设计的时候离职人员节点！！！
                        if (formId === 'leaveEmployee') {
                            return null;
                        }

                        // 根据期望离职日期赋值公积金/社保停缴月份
                        if (formId === 'socialSecurity') {
                            item.initialValue = initialValue || moment(hopeResignationDate).month() + 1;
                        }

                        //  剩余假期结算方式如果选择了折现，有折算金额编辑权限的需要显示
                        if (formId === 'vacationAmount') {
                            const v = form.getFieldValue('turnoverCommonYear');
                            if (v !== 2) {
                                return null;
                            }
                            return (
                                <Form.Item label={label} key={formId} extra={extra} {...wrapperLayout}>
                                    <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                                        {getFieldDecorator(formId, {
                                            initialValue,
                                            rules
                                        })(
                                            <AutoRenderComponent
                                                form={form}
                                                config={item}
                                                {...propsObj}
                                                style={{ flex: 1 }}
                                            />
                                        )}
                                        <Popover
                                            content={
                                                <div style={{ width: 320 }}>
                                                    请按本国货币输入金额。例如，国内请输入人民币金额，新加坡请输入新币金额。
                                                </div>
                                            }
                                            placement="top"
                                            getPopupContainer={e => e.parentElement}
                                        >
                                            <Icon
                                                type="question-circle"
                                                style={{ marginLeft: 5, display: 'flex', alignItems: 'center' }}
                                            />
                                        </Popover>
                                    </div>
                                </Form.Item>
                            );
                        }

                        return (
                            <React.Fragment key={formId}>
                                <Form.Item label={label} key={formId} extra={extra}>
                                    {getFieldDecorator(formId, {
                                        initialValue,
                                        rules
                                    })(<AutoRenderComponent form={form} config={item} {...propsObj} />)}
                                </Form.Item>
                            </React.Fragment>
                        );
                    })}

                <Form.Item style={{ display: 'none' }}>
                    {getFieldDecorator('pendingApprovers', {
                        initialValue: list.find(item => item.formId === 'pendingApprovers')?.initialValue || []
                    })(<Input />)}
                </Form.Item>
            </Spin>
        </div>
    );
};

export default Handover;
